<?php

namespace app\common\lib\exception;
use think\exception\Handle;
use think\facade\Request;

class ExceptionHandler extends Handle
{

    private $code;
    private $msg;
    private $errorCode;
    private $errorField;
    private $loginUrl = '/admin/login/index';

    // 需要返回客户端当前请求的URL路径

    public function render(\Exception $e)
    {
        if ($e instanceof BaseException)
        {
            //如果是自定义的异常
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
            if (isset($e->errorField)) $this->errorField = $e->errorField;
        }
        else
        {
//            Config::get('app_debug');
            if (Request::isAjax()) {
                $this->code = 1;
                $this->msg = $e->getMessage();
                $this->errorCode = 1;
                trace($e->getMessage(), 'error');
            } else {
                if ($e->getMessage() == 'no_login') {
                    echo '<script>top.window.location.href = "' . $this->loginUrl . '";</script>';
                    exit;
                }
                return parent::render($e);
            }
        }

        $result = [
            'msg' => $this->msg,
            'code' => $this->errorCode,
            'request_url' => Request::url()
        ];
        if ($this->errorField)  {
            $result['error_field'] = $this->errorField;
        }

        if ($this->msg == 'no_login') {
            $result['url'] = $this->loginUrl;
        }

        // 捕获系统异常时，还是返回正确的请求结果，只是结果中包含相应的错误code
        return json($result);
    }
}